//
//  AssignHomeWorkViewController.m
//  ChatDemo-UI2.0
//
//  Created by syun on 16/5/24.
//  Copyright © 2016年 syun. All rights reserved.
//
/**
 [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
 
 make.top.equalTo(headView.mas_bottom).offset(20);
 make.height.equalTo(@20);
 make.width.equalTo(@300);
 make.centerX.equalTo(headView.mas_centerX).offset(0);
 
 }];
 
 [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
 
 make.left.equalTo(self.view.mas_left).offset(0);
 make.right.equalTo(self.view.mas_right).offset(0);
 make.top.equalTo(self.view.mas_top).offset(0);
 make.height.equalTo(@220);
 }];
 
 */
#import "AssignHomeWorkViewController.h"
#import "TZImagePickerController.h"
#import "XZPhotobrowserViewController.h"
#import "LSSelectPhotoMenuItem.h"
#import "MenuButton.h"
#import <AVFoundation/AVFoundation.h>

#import "ClassListTableViewCell.h"

#import "SYChooseObjViewController.h"
#import "ClassesModel.h"
#import "StudentsModel.h"
#import "DropDownMenu2.h"
#import "AssignStuHomeWorkViewController.h"
#define IS_IPHONE4 (([[UIScreen mainScreen] bounds].size.height-480)?NO:YES)
#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)



@interface AssignHomeWorkViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,LSSelectPhotoItemDelegate,
changeImageDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate,DropDownMenu2Delegate>
{
    NSMutableArray *imageArray;
    CGRect imageOrigalRect;
    //照片选择器
    TZImagePickerController *imagePickerVc;
    NSMutableArray *classnameArray;
    NSMutableArray *studentsArray;
    NSMutableArray *selcetStuidArray;
    NSString *classid;//选择的学生所在的班级id
    
    BOOL isOriginflag;  //是否是原图
    
    UIView *ypView;
    UIImageView *ypImageView;
    UILabel *ypLabel;
    UIButton *ypButton;
    BOOL isSelectYP;
}
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) DropDownMenu2 *dropList;
@end

@implementation AssignHomeWorkViewController
- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle= UIModalPresentationOverFullScreen;
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.nav_titleLabel.text=@"班级作业";
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(popout:)];
    [self.navigationItem setLeftBarButtonItem:backItem];
   
   self.navBar.rightImg.hidden = NO;
   self.navBar.rightButton.hidden = NO;
   self.navBar.rightImg.image = [UIImage imageNamed:@"ios_more_"];
   [self.navBar.rightButton addTarget:self action:@selector(pushStuNoti:) forControlEvents:UIControlEventTouchUpInside];
   
    
    imageArray=[NSMutableArray array];
    selcetArray=[NSMutableArray array];
    imageIdArray = [[NSMutableArray alloc] initWithCapacity:0];
    classnameArray=[NSMutableArray array];
    studentsArray=[NSMutableArray array];
    selcetClassidArray=[NSMutableArray array];
    selcetStuidArray=[NSMutableArray array];
    
    [self loadClasses];
    [self loadTableView];
    [self creatUI];
    [self keyBtn];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chooseObjAction:) name:@"senderNotification" object:nil];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    // Do any additional setup after loading the view.
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int  height = keyboardRect.size.height;
    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight-height);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  sureBtn.frame.origin.y+sureBtn.frame.size.height+20);
}
//当键退出时调用

- (void)keyboardWillHide:(NSNotification *)aNotification

{
    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  sureBtn.frame.origin.y+sureBtn.frame.size.height+20);
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)pushStuNoti:(UIButton *)sender
{
    UIWindow *window=KeyWindow;
    _dropList = [DropDownMenu2 shareDropDownMenu];
    _dropList.delegate = self;
    _dropList.backViewFlag = 1;
    _dropList.flag = YES;
    [window addSubview:_dropList];
    
    [_dropList setDropDownMenuParameterWithcellContents:[NSArray arrayWithObjects:@"发至班级宝宝", nil] andWidth:130];
    [_dropList hideDropDown:sender];
}

#pragma mark -- DelegateMethod
- (void) niDropDownDelegateMethod:(DropDownMenu2 *) sender{
    
    if (_listArray.count>0) {
        
        AssignStuHomeWorkViewController *vc =[[AssignStuHomeWorkViewController alloc]init];
        vc.classArray = _listArray;
        [self.navigationController pushViewController:vc animated:YES];
    }else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先创建/加入班级" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag=111;
        [alert show];
        
    }
    
    
}

-(void)chooseObjAction:(NSNotification *)object
{
    NSDictionary *dic=object.userInfo;
    NSArray *array=[dic objectForKey:@"re_data"];

    [studentsArray removeAllObjects];
    for (StudentsModel *model in array) {
        [studentsArray addObject:model.studentname];
        [selcetStuidArray addObject:[NSString stringWithFormat:@"%ld",(long)model.studentid]];
        classid=[NSString stringWithFormat:@"%ld",(long)model.classid];
    }
    NSString *studentes=[studentsArray componentsJoinedByString:@","];
    ClassText.text=[NSString stringWithFormat:@" %@",studentes];
    arrowImage.image=[UIImage imageNamed:@"serch_del_nor_"];

    
}
-(void)creatUI
{
    _BackScrollView=[[UIScrollView alloc]init];
    _BackScrollView.delegate=self;
    _BackScrollView.userInteractionEnabled=YES;
    _BackScrollView.scrollEnabled=YES;
    _BackScrollView.backgroundColor=RGBACOLOR(239, 239, 244, 1);
    [self.view addSubview:_BackScrollView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelKeyBoard:)];
    tap.delegate=self;
    [_BackScrollView addGestureRecognizer:tap];
    //班级标签
    ClassMarkLabel=[[UILabel alloc]init];
    ClassMarkLabel.text=@"选择对象";
    ClassMarkLabel.textColor=RGBACOLOR(59, 59, 59, 1);
    [_BackScrollView addSubview:ClassMarkLabel];
    
    //班级内容
    ClassText=[[UITextField alloc]init];
    ClassText.placeholder=@" 请选择对象";
    ClassText.font=[UIFont systemFontOfSize:15];
    ClassText.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:ClassText];
    
    arrowView=[[UIView alloc]init];
    arrowView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:arrowView];
    //箭头
    arrowImage=[[UIImageView alloc]init];
    arrowImage.backgroundColor=[UIColor whiteColor];
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];
    [arrowView addSubview:arrowImage];
    
    
    //选择班级按钮
    selectClassBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [selectClassBtn addTarget:self action:@selector(openClassList:) forControlEvents:UIControlEventTouchUpInside];
    [_BackScrollView addSubview:selectClassBtn];
    
    [ClassMarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).offset(12);
//        if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
//            make.top.equalTo(self->_BackScrollView.mas_top).offset(20);
//        }else
//        {
            make.topMargin.equalTo(_BackScrollView.mas_top).offset(20);
//        }
        make.height.equalTo(@30);
        make.width.equalTo(@70);
        
    }];
    
    [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@30);
        make.width.equalTo(@28);
        make.top.equalTo(self->ClassMarkLabel.mas_top).offset(0);
        make.right.equalTo(self.view.mas_right).offset(-12);
    }];
    [arrowImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@18);
        make.width.equalTo(@18);
        make.top.equalTo(self->arrowView.mas_top).offset(6);
        make.right.equalTo(self->arrowView.mas_right).offset(-5);
    }];
    
    [ClassText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->ClassMarkLabel.mas_top).offset(0);
        make.height.equalTo(@30);
        make.left.equalTo(self->ClassMarkLabel.mas_right).offset(12);
        make.right.equalTo(self->arrowView.mas_left).offset(0);
    }];
    
    [selectClassBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->ClassMarkLabel.mas_top).offset(0);
        make.height.equalTo(@30);
        make.left.equalTo(self->ClassMarkLabel.mas_right).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        
    }];
    
    //编辑内容
    ContentmarkLabel=[[UILabel alloc]init];
    ContentmarkLabel.text=@"编辑内容";
    ContentmarkLabel.textColor=RGBACOLOR(59, 59, 59, 1);
    [_BackScrollView addSubview:ContentmarkLabel];
    
    ContentTextView=[[UITextView alloc]init];
    ContentTextView.delegate=self;
    ContentTextView.userInteractionEnabled=YES;
    ContentTextView.backgroundColor=[UIColor whiteColor];
    ContentTextView.font=[UIFont systemFontOfSize:15];
    ContentTextView.text=@"请编辑作业内容";
    ContentTextView.textColor=RGBACOLOR(199, 199, 204, 1);
    [_BackScrollView addSubview:ContentTextView];
    
    [ContentmarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self->arrowImage.mas_right).offset(0);
        make.top.equalTo(self->ClassMarkLabel.mas_bottom).offset(20);
        make.height.equalTo(@30);
    }];
    
    [ContentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self->arrowView.mas_right).offset(0);
        make.top.equalTo(self->ContentmarkLabel.mas_bottom).offset(10);
        make.height.equalTo(@160);
        
    }];
    //图片 文字
    
    backView=[[UIView alloc]init];
    backView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:backView];
    
    addPicView=[[UIView alloc]init];
    [backView addSubview:addPicView];
    
    //相机图片
    PhotoPic=[[UIImageView alloc]init];
    PhotoPic.userInteractionEnabled=YES;
    PhotoPic.image=[UIImage imageNamed:@"carmer_content_"];
    [addPicView addSubview:PhotoPic];
    
    
    //添加图片四个字
    MarkLabel=[[UILabel alloc]init];
    MarkLabel.text=@"添加图片";
    MarkLabel.textColor=RGBACOLOR(56, 173, 255, 1);
    MarkLabel.font=[UIFont systemFontOfSize:14];
    [addPicView addSubview:MarkLabel];
    
    //添加照片按钮
    addPic=[UIButton buttonWithType:UIButtonTypeCustom];
    [addPic addTarget:self action:@selector(selectPics:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:addPic];
    
    WordCountLabel=[[UILabel alloc]init];
    WordCountLabel.textColor=RGBACOLOR(199, 199, 204, 1);
    WordCountLabel.font=[UIFont systemFontOfSize:11];
    WordCountLabel.textAlignment=NSTextAlignmentRight;
    WordCountLabel.text=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %@/200" ,@"0"];
    [backView addSubview:WordCountLabel];
    
    
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self->arrowView.mas_right).offset(0);
        make.top.equalTo(self->ContentTextView.mas_bottom).offset(0);
        make.height.equalTo(@25);
        
    }];
    
    [addPicView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self->backView.mas_left).offset(10);
        make.bottom.equalTo(self->backView.mas_bottom).offset(-5);
        make.width.equalTo(@100);
        make.height.equalTo(@22);
    }];
    
    [PhotoPic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->addPicView.mas_left).offset(0);
        make.bottom.equalTo(self->addPicView.mas_bottom).offset(0);
        make.width.equalTo(@22);
        make.height.equalTo(@22);
    }];
    
    [MarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->PhotoPic.mas_right).offset(5);
        make.bottom.equalTo(self->addPicView.mas_bottom).offset(0);
        make.width.equalTo(@70);
        make.height.equalTo(@17);
    }];
    
    [addPic mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self->backView.mas_left).offset(10);
        make.bottom.equalTo(self->backView.mas_bottom).offset(-5);
        make.width.equalTo(@100);
        make.height.equalTo(@22);
    }];
    
    [WordCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self->backView.mas_right).offset(-5);
        make.bottom.equalTo(self->backView.mas_bottom).offset(-5);
        make.height.equalTo(@17);
        make.width.equalTo(@210);
    }];
    
    //照片
    picsBackView=[[UIView alloc]init];
    picsBackView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:picsBackView];
    
    [picsBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.top.equalTo(self->backView.mas_bottom).offset(0);
        make.height.equalTo(@0);
    }];
    
    
    _takePictureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_takePictureBtn addTarget:self action:@selector(selectPics:) forControlEvents:UIControlEventTouchUpInside];
    [_takePictureBtn setImage:[UIImage imageNamed:@"pic_content_"] forState:UIControlStateNormal];
    [picsBackView addSubview:_takePictureBtn];
    
    
//    ypView = [[UIView alloc]init];
//    ypView.userInteractionEnabled = YES;
//    ypView.hidden=YES;
//    
//    
//    ypImageView = [[UIImageView alloc]init];
//    ypImageView.image =[UIImage imageNamed:@"choose_no_nor_"];
//    ypImageView.userInteractionEnabled = YES;
//    [ypView addSubview:ypImageView];
//    
//    ypLabel = [[UILabel alloc]init];
//    ypLabel.text = @"图片同时上传至班级云盘";
//    ypLabel.font =[UIFont systemFontOfSize:14];
//    ypLabel.textColor = [UIColor colorWithHexString:@"#979797"];
//    ypLabel.userInteractionEnabled = YES;
//    [ypView addSubview:ypLabel];
//    
//    
//    ypButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [ypButton addTarget:self action:@selector(selectUpYP:) forControlEvents:UIControlEventTouchUpInside];
//    [ypView addSubview:ypButton];
//    
//    [_BackScrollView addSubview:ypView];
//   
//    [ypView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.equalTo(self->picsBackView.mas_bottom).offset(12);
//        make.left.equalTo(self.view.mas_right).offset(-200);
//        make.height.equalTo(@30);
//        make.width.equalTo(@200);
//        
//    }];
//    
//    [ypImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.equalTo(self->ypView.mas_left).offset(0);
//        make.height.equalTo(@16);
//        make.width.equalTo(@16);
//        make.top.equalTo(self->ypView.mas_top).offset(0);
//    }];
//    
//    [ypLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.equalTo(self->ypImageView.mas_right).offset(6);
//        make.height.equalTo(@14);
//        make.width.equalTo(@166);
//        make.top.equalTo(self->ypView.mas_top).offset(1);
//    }];
//    
//    
//    [ypButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.equalTo(self->ypView.mas_left).offset(0);
//        make.height.equalTo(@30);
//        make.width.equalTo(@200);
//        make.top.equalTo(self->ypView.mas_top).offset(0);
//    }];
    
    
    sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.layer.cornerRadius=5;
    [sureBtn setBackgroundColor:RGBACOLOR(57, 173, 255, 1)];
    [sureBtn setTitle:@"提交" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [_BackScrollView addSubview:sureBtn];
    
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.height.equalTo(@38);
        make.top.equalTo(self->picsBackView.mas_bottom).offset(50);
    }];
    
    //    [_BackScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.equalTo(self.view);
    //        make.bottom.equalTo(self->sureBtn.mas_bottom).offset(20);
    //    }];
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
    
    _BackScrollView.contentSize =CGSizeMake(SCREENWIDTH, sureBtn.frame.size.height+sureBtn.frame.origin.y+20);
    
}


#pragma --创建班级选择列表
-(void)loadTableView
{
    classControl=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREENHEIGH)];
    classControl.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"toumingbg"]];
    
    UIView *classView=[[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-152,50 + 64, 140, 227)];
    classView.backgroundColor=[UIColor clearColor];
    
    UIImageView *classImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, classView.frame.size.width, classView.frame.size.height)];
    classImageView.image=[UIImage imageNamed:@"listdrop_checkbox_four_"];
    [classView addSubview:classImageView];
    
    classTable=[[UITableView alloc]initWithFrame:CGRectMake(0, 9, classImageView.frame.size.width, classImageView.frame.size.height-40-9) style:UITableViewStylePlain];
    classTable.delegate=self;
    classTable.dataSource=self;
    classTable.backgroundColor=[UIColor clearColor];
    classTable.showsVerticalScrollIndicator =NO;
    [classTable setSeparatorColor:[UIColor clearColor]];
    
    chooseClass=[UIButton buttonWithType:UIButtonTypeCustom];
    chooseClass.frame=CGRectMake(40, classView.frame.size.height-32.5, 60, 25);
    [chooseClass setImage:[UIImage imageNamed:@"sure_list_nor_"] forState:UIControlStateNormal];
    [chooseClass addTarget: self action:@selector(chooseClassesAction:) forControlEvents:UIControlEventTouchUpInside];
    [classView addSubview:classTable];
    [classView addSubview:chooseClass];
    [classControl addSubview:classView];
    [classControl addTarget:self action:@selector(cancelClassList) forControlEvents:UIControlEventTouchUpInside];
    
}


- (void) selectUpYP:(UIButton *)sender
{
    isSelectYP = !isSelectYP;
    
    if (isSelectYP) {
        
        ypImageView.image =[UIImage imageNamed:@"choose_ok_press_"];
        
    }else
    {
        ypImageView.image =[UIImage imageNamed:@"choose_no_nor_"];
    }
}
#pragma --tableViewdelegate
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    
    return [_listArray count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *key=@"cell";
    ClassListTableViewCell *cell=(ClassListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:key];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ClassListTableViewCell" owner:self options:nil]objectAtIndex:0];
    }
    cell.backgroundColor=[UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.className.text=[[_listArray objectAtIndex:indexPath.row] objectForKey:@"classname"];
    
    if (selcetArray.count>0) {
        if ([[selcetArray objectAtIndex:indexPath.row]isEqualToString:@"no"]) {
            
            cell.className.textColor=[UIColor colorWithHexString:@"3b3b3b"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_nor_"];
        }else
        {
            cell.className.textColor=[UIColor colorWithHexString:@"39adff"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_press_"];
        }
    }
    
    cell.tag=indexPath.row+100;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassListTableViewCell *cell=[classTable cellForRowAtIndexPath:indexPath];//获取当前点击cell
    int i=(int)(cell.tag-100);
    if (selcetArray.count>0) {
        if ([[selcetArray objectAtIndex:i]isEqualToString:@"no"]) {
            [selcetArray replaceObjectAtIndex:i withObject:@"yes"];
            cell.className.textColor=[UIColor colorWithHexString:@"39adff"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_press_"];
            classCount--;
        }else
        {
            [selcetArray replaceObjectAtIndex:i withObject:@"no"];
            cell.className.textColor=[UIColor colorWithHexString:@"3b3b3b"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_nor_"];
            classCount++;
        }
    }
    
    if (classCount<selcetArray.count) {
        [chooseClass setImage:[UIImage imageNamed:@"sure_list_hl_"] forState:UIControlStateNormal];
    }else
    {
        [chooseClass setImage:[UIImage imageNamed:@"sure_list_nor_"] forState:UIControlStateNormal];
    }
}
#pragma --选择班级
-(void)openClassList:(UIButton *)sender
{

    [ContentTextView resignFirstResponder];
    
    UIWindow *window = KeyWindow;
    [window addSubview:classControl];
    
}
-(void)chooseClassesAction:(UIButton *)sender
{
    NSMutableArray *selcetClassArray=[NSMutableArray array];
    selcetClassidArray=[NSMutableArray array];
    //    AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
    for (int i=0; i<selcetArray.count; i++) {
        if ([[selcetArray objectAtIndex:i] isEqualToString:@"yes"]) {
            [selcetClassArray addObject:[[_listArray objectAtIndex:i] objectForKey:@"classename"]];
            [selcetClassidArray addObject:[[_listArray objectAtIndex:i] objectForKey:@"classid"]];
        }
    }
    NSString *classes=[selcetClassArray componentsJoinedByString:@","];
    ClassText.text=[NSString stringWithFormat:@" %@",classes];
    [classControl removeFromSuperview];
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];
    
}
-(void)cancelClassList
{
    [classControl removeFromSuperview];
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];
}

#pragma mark - 提交
-(void)submitAction:(UIButton *)sender
{
    if (ClassText.text.length == 0) {
        [Utils alertViewWithMessage:@"请选择班级"];
        return;
    }
    
    if ([imageArray count]) {
        if ([ContentTextView.text isEqualToString:@"请编辑作业内容"]) {
            ContentTextView.text=@"作业内容,请点击进入查看图片信息。";
        }
        
        for (int i = 0; i < imageArray.count; i++) {
            
            
            UIImage *image = imageArray[i];
            
        
            UIImageOrientation imageOrientation = image.imageOrientation;
            
            if (imageOrientation != UIImageOrientationUp) {
                
                UIGraphicsBeginImageContext(image.size);
                [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
                image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
            }
            
            imageOrientation = image.imageOrientation;
            
            NSData * fileData;
            if (!isOriginflag) {
                //压缩图片
                image = [Utils imageWithImage:image];
                
                fileData = UIImageJPEGRepresentation(image, 0.5);
                
                if (fileData.length > 1024 * 200) {
                    
                    fileData = UIImageJPEGRepresentation(image, 0.2);
                }
            }else{
                
                fileData = UIImageJPEGRepresentation(image, 1);
                if (fileData.length > 2*1024* 1024) {
                    int n=1;float f=0.9;
                    for (int i=0; i<n; i++) {
                        fileData = UIImageJPEGRepresentation(image, f);
                        if (fileData.length >  2*1024* 1024) {
                            f-=0.1;
                            n++;
                        }
                    }
                }
                
            }
            
            
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
            [dict setObject:@"InsertfileInfo" forKey:@"method"];
            [dict setObject:@"1" forKey:@"typeid"];
            [dict setObject:[fileData base64Encoding] forKey:@"file"];
            [dict setObject:@"11" forKey:@"filename"];
            [dict setObject:@"file" forKey:@"description"];
            [dict setObject:@".jpg" forKey:@"kz"];
            dict  = [Utils completeImageSubmitParameterWith:dict];
            NSString * postValue = [Utils getXMLStringWithParameter:dict];
            
            [Utils submitImageToWebService:SUBMITIMAGEURL SOAPActionSring:@"http://tempuri.org/InsertfileInfo" postValue:postValue success:^(NSInteger recode, id resposeJson){
                NSDictionary * dict = (NSDictionary *)resposeJson;
                NSString * returncode = [dict objectForKey:@"returncode"];
                if ([returncode isEqualToString:@"10000"]) {
                    [self hideHud];
                    //                    [self showHint:NSLocalizedString(@"setting.uploadSuccess", @"uploaded successfully")];
                    [self->imageIdArray addObject:[dict objectForKey:@"id"]];
                    if ([self ->imageArray count] == [self->imageIdArray count]) {
                        
                        
                        [self claSubmitHomework:YES];
                        
                    }
                    return ;
                }else
                {
                    [self hideHud];
                    return ;
                }
            } failure:^(NSInteger recode, NSError * error){
                [self hideHud];
                [self showHint:NSLocalizedString(@"setting.uploadFail", @"uploaded failed")];
                return ;
            }];
        }
        
    }else
    {
        if ([ContentTextView.text isEqualToString:@"请编辑作业内容"] ) {
            [Utils alertViewWithMessage:@"请将作业内容填写完整"];
            return;
        }
        if ([[ContentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
        {
            [Utils alertViewWithMessage:@"请将作业内容填写完整"];
            return;
        }
        if (ContentTextView.text.length>200) {
            [Utils alertViewWithMessage:@"请将作业内容限制在200字以内"];
            return;
        }
        BOOL contentcontains = [Utils stringContainsEmoji:ContentTextView.text];
        if (contentcontains) {
            [Utils alertViewWithMessage:@"作业内容中不能含有特殊字符"];
            return;
        }
        
        [self claSubmitHomework:NO];
    }
}
- (void)claSubmitHomework:(BOOL)submitFile
{
    NSString *classids;
    if (selcetClassidArray.count>0) {
        classids=[selcetClassidArray componentsJoinedByString:@","];
    }else {
        return;
    }
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_add" forKey:@"method"];
    [dict setObject:classids forKey:@"classid"];
    [dict setObject:@"3" forKey:@"type"];
    [dict setObject:@"1" forKey:@"isSendMsg"];
    [dict setObject:USERID forKey:@"userid"];
    [dict setObject:@"0" forKey:@"studentid"];
    [dict setObject:ContentTextView.text forKey:@"scontent"];
    
    if (submitFile) {
        NSString *filesString = [imageIdArray componentsJoinedByString:@","];
        [dict setObject:filesString forKey:@"fileid"];
    }
    
    if (isSelectYP) {
        
        [dict setObject:@"1" forKey:@"isaddclassfile"];
    }else
    {
        [dict setObject:@"0" forKey:@"isaddclassfile"];
    }
    
    
    [Utils post:nil parameters:dict success:^(NSInteger recode, id resposeJson) {
        
        self->userdict = (NSDictionary *)resposeJson;
        
//        UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:nil message:[self->userdict objectForKey:@"re_info"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        alert.tag=101;
//        [alert show];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SYAccountTool ShareAccount].needRefresh = 1;
            [self.navigationController popViewControllerAnimated:YES];
            
//            id num=[self->userdict objectForKey:@"integalnum"];
//            if (![num isKindOfClass:[NSNull class]]) {
//                NSString *n=num;
//                if ([n intValue]>0) {
//                    
//                    [self->_delegate showYunDouAlert:@"留作业" andNum:[n intValue]];
//                    
//                }
//            }
        });
        
    } failure:^(NSInteger recode, NSError * error){
        
         [self showHint:@"网络异常,请稍后重试!"];
    }];
}

#pragma --选择图片
-(void)selectPics:(UIButton *)sender
{
    [ContentTextView resignFirstResponder];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"相册上传", nil];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
}
#pragma --nav按钮方法
-(void)popout:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)PushHistoryHomeWork:(UIButton *)sender
{
    
}
#pragma mark -UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 2) { //取消
        return;
    }
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    
    imagePicker.allowsEditing = YES;
    
    if (buttonIndex == 0) {  //照相机
        NSString *mediaType = AVMediaTypeVideo;
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置－隐私－相机”中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag=201;
            [alert show];
            
        }else
        {
            
            imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(__bridge NSString *)kUTTypeImage, nil];
            
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
        
    }else{  //图库
        
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 - imageArray.count delegate:self];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (orgImage != nil) {
        [imageArray addObject:orgImage];
        addPicView.hidden=YES;
        [self relignmentImageButton];
    }
}

- (void)relignmentImageButton
{
    for (UIView *view in picsBackView.subviews) {
        
        if ([view isKindOfClass:[MenuButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    CGFloat hirizontalGap = 10;
    CGFloat picHeight=(SCREENWIDTH-24-40)/3;
    CGFloat picWidth=(SCREENWIDTH-24-40)/3;
    
    for (NSInteger imageIndex = 0 ; imageIndex <= [imageArray count]; imageIndex ++) {
        
        CGRect btnRect = CGRectMake(10 + (hirizontalGap + picWidth)* (imageIndex % 3) , 10 + (hirizontalGap + picHeight) * (imageIndex / 3),picWidth, picHeight);
        
        if (imageIndex == [imageArray count]) {
            
            
            if (imageIndex == 9)
            {
                btnRect = CGRectMake(10 + (hirizontalGap + picWidth)* (8 % 3) , 10 + (hirizontalGap + picHeight) * (8 / 3),picWidth, picHeight);
                _takePictureBtn.hidden = YES;
                
            }
            else
            {
                //全部删除图片 picsBackView不显示
                if(imageArray.count==0) {
                    _takePictureBtn.hidden = YES;
                    [picsBackView mas_updateConstraints:^(MASConstraintMaker *make) {
                        
                        make.height.equalTo(@0);
                        
                    }];
                    [picsBackView setHeight:0];
                    
//                    [sureBtn mas_updateConstraints:^(MASConstraintMaker *make) {
//                        make.top.equalTo(self->picsBackView.mas_bottom).offset(50);
//                        
//                    }];
                    [sureBtn setY:picsBackView.bottom + 50];
                    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
                    
                    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH, sureBtn.frame.origin.y+sureBtn.frame.size.height+20+38+50);
                    
                    
                    addPicView.hidden=NO;
                    ypView.hidden = YES;
                    return;
                }
                _takePictureBtn.hidden = NO;
                _takePictureBtn.frame=btnRect;
            }
            
            ypView.hidden = NO;
            
            [picsBackView mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.height.equalTo(@(CGRectGetMaxY(btnRect)+10));
            }];
            
            [picsBackView setHeight:CGRectGetMaxY(btnRect)+10];
            
            [sureBtn setY:picsBackView.bottom + 50];

            
            _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
            
            _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH, sureBtn.frame.origin.y+sureBtn.frame.size.height+20+38+50);
            
            return;
        }
        MenuButton * iamgeBtn = [MenuButton buttonWithType:UIButtonTypeCustom];
        [iamgeBtn setFrame:btnRect];
        iamgeBtn.tag = imageIndex;
        [iamgeBtn addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
        iamgeBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
        [iamgeBtn setImage:[imageArray objectAtIndex:imageIndex] forState:UIControlStateNormal];
        
        [picsBackView addSubview:iamgeBtn];
        
        [picsBackView layoutSubviews];
        
        _BackScrollView.frame=CGRectMake(0,SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
        
        _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH, sureBtn.frame.origin.y+sureBtn.frame.size.height+20+38+50);
    }
    
}


- (void)deletePicture:(MenuButton *)sender
{
    XZPhotobrowserViewController *vc = [[XZPhotobrowserViewController alloc] init];
    vc.index_Current = sender.tag+1;
    vc.arrayOK = imageArray;
    vc.delegate = self;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -TZImagePickerDelegate
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets{
    
    
    
    id obj = assets[0];
    
    if (![obj isKindOfClass:[NSNumber class]]) {  //不是原图
        
        isOriginflag = YES;
    }
    
    
    
    [imageArray addObjectsFromArray:photos];
    addPicView.hidden=YES;
    
    [self relignmentImageButton];
}

#pragma mark -ChangeImageDelegate
-(void)changeImageWithArray:(NSMutableArray *)arr{
    
    [imageArray removeAllObjects];
    [imageArray addObjectsFromArray:arr];
    
    [self relignmentImageButton];
}
-(void)loadClasses
{
    if (_listArray.count>0) {
        for (int i=0; i<_listArray.count; i++) {
            [selcetArray addObject:@"no"];
        }
        classCount=(int)selcetArray.count;
    }else
    {
        AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
        NSString *lasttype = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:@"api_classone_search" forKey:@"method"];
        [dict setObject:@"1" forKey:@"pageno"];
        [dict setObject:@"1000000000" forKey:@"pagesize"];
        [dict setObject:lasttype forKey:@"type"];
        [dict setObject:USERID forKey:@"userid"];
        [dict setObject:@"1" forKey:@"state"];
        [Utils getAllClass:nil parameters:dict success:^(NSInteger recode, id resposeJson){
            NSDictionary *dict = (NSDictionary *)resposeJson;
            delegate.myClasses = [dict objectForKey:@"re_data"];
            if (delegate.myClasses.count>0) {
                for (int i=0; i<delegate.myClasses.count; i++) {
                    [self->selcetArray addObject:@"no"];
                    
                }
                self->classCount=(int)[self->selcetArray count];
                self->_listArray=delegate.myClasses;
            }else
            {
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有班级，请先创建班级或加入班级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag=111;
                [alert show];
                
            }
            
            
        } failure:^(NSInteger recode, NSError * error){
            
        }];
    }
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==111) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        UIViewController * view = nil;
        view = [storyboard instantiateViewControllerWithIdentifier:@"ClassTeamViewController"];
        
        if (view != nil) {
            [self.navigationController pushViewController:view animated:YES];
        }
    }
    else if (alertView.tag==101) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SYAccountTool ShareAccount].needRefresh = 1;
            [self.navigationController popViewControllerAnimated:YES];
            
            id num=[self->userdict objectForKey:@"integalnum"];
            if (![num isKindOfClass:[NSNull class]]) {
                NSString *n=num;
                if ([n intValue]>0) {
                    
                    [self->_delegate showYunDouAlert:@"留作业" andNum:[n intValue]];
                    
                }
            }
        });
    }
    
    
}
-(void)cancelKeyBoard:(UITapGestureRecognizer *)sender
{
    [ContentTextView resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma --uitextViewdelegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"请编辑作业内容"]) {
        textView.text=@"";
    }
    
    
    ContentTextView.textColor=[UIColor blackColor];
    
    
    return YES;
}
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    
}
//焦点发生改变
-(void)textViewDidChangeSelection:(UITextView *)textView
{
    
    if (textView.text.length > 200) {
        UITextRange *markedRange = [textView markedTextRange];
        if (markedRange) {
            return;
        }
        //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
        //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
        NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:200];
        textView.text = [textView.text substringToIndex:range.location];
    }
    
    NSString *str=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %lu/200",(unsigned long)textView.text.length];
    
    NSMutableAttributedString *string=[[NSMutableAttributedString alloc]initWithString:str];
    if (textView.text.length>190&&textView.text.length<999) {
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(16,3)];
    }
    WordCountLabel.attributedText=string;
}
//结束编辑

- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    if (textView.text.length==0) {
        
        ContentTextView.text=@"请编辑作业内容";
        ContentTextView.textColor=[UIColor lightGrayColor];
        WordCountLabel.text=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %@/200" ,@"0"];
    }
}
//限制EMOJI键盘输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // 不让输入表情
    if ([textView isFirstResponder]) {
        if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
            NSLog(@"输入的是表情，返回NO");
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不能输入表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
            [alertView show];
            return NO;
        }
    }
    return YES;
}
-(void)keyBtn
{
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    topView.backgroundColor=[UIColor whiteColor];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [topView setItems:buttonsArray];
    
    [ContentTextView setInputAccessoryView:topView];
}

-(void)dismissKeyBoard
{
    [ContentTextView resignFirstResponder];
    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  sureBtn.frame.origin.y+sureBtn.frame.size.height+20);
}

////内容发生改变编辑
//- (void)textViewDidChange:(UITextView *)textView
//{
//    WordCountLabel.text=[NSString stringWithFormat:@"请将您的文字限制在200字以内%lu/200",(unsigned long)textView.text.length];
//}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
